package ui;

import java.awt.Button;
import java.awt.Rectangle;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import util.ConfigurationManager;

import constants.CurrentConfigConstants;

public class ConfigWindow extends JPanel{
	
	UIManager foo = null;
	
	/**
	 * run
	 */
	public ConfigWindow(UIManager foo){
		
		this.foo = foo;
		setControl();
		setContentPanel();
		setListener();

	}
	
	///
	/// Control
	///
	JLabel lb_name = new JLabel();
	JLabel lb_port = new JLabel();
	JLabel lb_tip = new JLabel();
	
	JTextField tf_name = new JTextField();
	JTextField tf_port = new JTextField();
	
	Button btn_ok = new Button();
	Button btn_cancel = new Button();
	
	/**
	 * 设置控件
	 * @throws Exception
	 */
	private void setControl() {
		
		lb_name.setText("Name:");
		lb_port.setText("Port:");
		lb_tip.setText("设置在下次启动程序时生效");
		
		tf_name.setEditable(true);
		tf_name.setText(CurrentConfigConstants.CLIENT_CURRENT_NAME);
		
		tf_port.setEditable(true);
		tf_port.setText(CurrentConfigConstants.CLIENT_CURRENT_PORT);
		
		btn_cancel.setLabel("Cancel");
		btn_ok.setLabel("OK");
		
	}
	
	/**
	 * 设置主面板
	 * @throws Exception
	 */
	private void setContentPanel() {
		
		
		// 添加控件到面板
		this.add(lb_name, null);
		this.add(lb_port, null);
		this.add(lb_tip, null);
		this.add(tf_name, null);
		this.add(tf_port, null);
		this.add(btn_ok, null);
		this.add(btn_cancel, null);

		
		// 布局控制
		// X, Y , Width, Height
		this.setLayout(null);
		this.setBounds(5, 5, 450, 450);
		lb_name.setBounds(new Rectangle(5, 10, 95, 20));
		lb_port.setBounds(new Rectangle(5, 40, 95, 20));
		tf_name.setBounds(new Rectangle(105, 10, 95, 20));
		tf_port.setBounds(new Rectangle(105, 40, 95, 20));
		lb_tip.setBounds(new Rectangle(10, 130, 170, 20));
		btn_ok.setBounds(new Rectangle(100, 170, 80, 40));
		btn_cancel.setBounds(new Rectangle(5, 170, 80, 40));
	}
	
	/**
	 * 设置监听器
	 * @throws Exception
	 */

	private void setListener() {
		// btn_login 点击事件
		btn_ok.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
				ConfigurationManager conf = new ConfigurationManager();
				conf.loadConfig();
				conf.setValue("name", tf_name.getText());
				conf.setValue("port", tf_port.getText());
				conf.saveConfig("");
				
				foo.configWindow.setVisible(false);
				foo.mainWindow.setVisible(true);
			}
		});
		// btn_close 点击事件
		btn_cancel.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				foo.configWindow.setVisible(false);
				foo.mainWindow.setVisible(true);
			}
		});
	}
	
}
